import { useEffect, useRef, useState } from 'react'
import SignatureCanvas from 'react-signature-canvas'
import { Button, Form, Input, Space, Popup, ImageUploader, Toast, Image, Switch, Tag } from 'antd-mobile'
import { checkUpdate, checkTypeList } from '@api'
import { useParams, useNavigate } from 'react-router-dom'
import { parseInputDateTime, formatDateTimeForInput } from '@utils/index'
import { uploadFileToOSS } from '@utils/upload'
import { getWatermark } from '@utils/index'

import './index.scss'

const maxCount = 9
const TAB = [
    { title: '合格', val: 'PASS' },
    { title: '不合格', val: 'IN_RECTIFY' }
]

function SignaturePad() {
    const { shopId } = useParams()
    const navigate = useNavigate()

    const sigCanvas = useRef({})
    const sigCanvas2 = useRef({})
    const [visible, setVisible] = useState(false)
    const [visible1, setVisible1] = useState(false)
    const [visible2, setVisible2] = useState(false)

    const [fileList, setFileList] = useState([])

    const [options, setOptions] = useState([])

    const [typeIndex, setTypeIndex] = useState([])

    const [status, setStatus] = useState('PASS')

    const [checkTime, setCheckTime] = useState(formatDateTimeForInput())

    const [sign1, setSign1] = useState('')
    const [sign2, setSign2] = useState('')

    const [desc, setDesc] = useState('')

    const [record, setRecord] = useState([])

    const [rectifyRecord, setRectifyRecord] = useState([])

    const [details, setDetails] = useState({})

    const [showWatermark, setShowWatermark] = useState(false)
    const [watermark, setWatermark] = useState('')

    const [verifyRecordId, setVerifyRecordId] = useState('')

    useEffect(() => {
        checkTypeList().then(({ success, data }) => {
            if (success && data) {
                setOptions(data)
            }
        })
        // 渲染数据
        const obj = JSON.parse(localStorage.getItem('merchantDetail') || '{}')
        setDetails(obj)
        const { checkTime: time, records, inspectedSign, inspectorsSign, status: _status, checkTypeList: _checkTypeList, rectifyRecords: _rectifyRecords } = JSON.parse(localStorage.getItem('checkItem') || '{}')
        setSign1(inspectorsSign)
        setSign2(inspectedSign)
        setRecord(records)
        setRectifyRecord(_rectifyRecords)
        setStatus(_status)
        setTypeIndex(_checkTypeList.map((e) => e.id))
        setCheckTime(formatDateTimeForInput(time))
    }, [])

    useEffect(() => {
        console.log(record)
    }, [record])

    const fileInputRef = useRef(null)
    const fileInputRef2 = useRef(null)

    const handleButtonClick = () => {
        fileInputRef.current.click()
    }
    const handleButtonClick2 = () => {
        fileInputRef2.current.click()
    }

    const handleFileChange = (event) => {
        // 处理文件选择
        const file = event.target.files[0]
        uploadFileToOSS({ file }).then(({ res }) => {
            const url = res.requestUrls[0].split('?')[0]
            setSign1(url)
            clear(1)
            reset2()
        })
    }
    const handleFileChange2 = (event) => {
        // 处理文件选择
        const file = event.target.files[0]
        uploadFileToOSS({ file }).then(({ res }) => {
            const url = res.requestUrls[0].split('?')[0]
            setSign2(url)
            clear(2)
            reset2()
        })
    }

    const clear = (index) => {
        if (index === 1) {
            sigCanvas.current.clear()
        } else {
            sigCanvas2.current.clear()
        }
    }

    const save = (index) => {
        let image = ''
        if (index === 1) {
            image = sigCanvas.current.getTrimmedCanvas().toDataURL('image/png')
        } else {
            image = sigCanvas2.current.getTrimmedCanvas().toDataURL('image/png')
        }
        uploadFileToOSS({ file: image }).then(({ res }) => {
            const url = res.requestUrls[0].split('?')[0]
            if (index === 1) {
                setSign1(url)
            } else {
                setSign2(url)
            }
            clear(index)
            reset2()
        })
    }

    // 重置
    const reset = () => {
        setVisible(false)
        setFileList([])
        setDesc('')
        setVerifyRecordId('')
    }

    const reset2 = () => {
        setVisible1(false)
        setVisible2(false)
    }

    // 提交
    const submit = () => {
        const { id } = JSON.parse(localStorage.getItem('checkItem') || '{}')
        // 先独立生成 records 数组，方便后续判断
        const records = status === 'PASS'
            ? []
            : record.map(item => {
                const verifyRecord = rectifyRecord.find(e => e.verifyRecordId === item.id);
                return {
                    merchantVerifyRecordAction: item,
                    ...(verifyRecord ? { merchantRectifyRecordAction: { ...verifyRecord } } : {})
                };
            });

        // 判断逻辑：
        // 1. 当原状态不是 PASS 时，才需要判断整改状态
        // 2. 使用 every() 确保所有记录都有验证记录
        // 3. 空数组 (PASS 状态) 时无需处理，保持原状态
        const isAllRectified = records.every(r => r.merchantRectifyRecordAction);
        const shouldRectify = status !== 'PASS' && !isAllRectified;

        const params = {
            id,
            checkTime: parseInputDateTime(checkTime),
            checkTypeIds: typeIndex,
            inspectedSign: sign2,
            inspectorsSign: sign1,
            merchantId: shopId,
            records,
            rectifyDay: shouldRectify ? 7 : 0,    // 需要整改时给 7 天
            status: shouldRectify ? 'IN_RECTIFY' : (status === 'PASS' ? status : 'HAVING_RECTIFY')
        };
        checkUpdate(params).then(({ success, info }) => {
            Toast.show(info)
            if (success) {
                navigate(-1)
            }
        })
    }

    // 上传
    const upload = async (file) => {
        let result = null
        if (showWatermark) {
            result = await getWatermark(file, watermark)
        }
        const { res } = await uploadFileToOSS({ file: result || file })
        try {
            return { url: res.requestUrls[0].split('?')[0] }
        } catch (error) {
            throw new Error(error)
        }
    }

    // 添加记录
    const add = () => {
        if (verifyRecordId) {
            setRectifyRecord((prev) => [...prev, { title: desc, imageList: fileList.map((e) => e.url), verifyRecordId: verifyRecordId, status: true }])
        } else {
            setRecord((prev) => [...prev, { title: desc, imageList: fileList.map((e) => e.url) }])
        }
        setVisible(false)
    }

    const del = (index) => {
        setRecord((prev) => prev.filter((_, idx) => idx !== index))
    }

    const del2 = (id) => {
        setRectifyRecord((prev) => prev.filter((item) => item.verifyRecordId !== id))
    }

    return (
        <div className="Add">
            <div className="Add_info">
                <div>
                    <p>单位：</p>
                    <p>{details.unit}</p>
                </div>
                <div>
                    <p>负责人：</p>
                    <p>{details.headName}</p>
                </div>
                <div>
                    <p>电话：</p>
                    <p>{details.headPhone}</p>
                </div>
                <div>
                    <p>行业类型：</p>
                    <p>{details.trade}</p>
                </div>
                <div>
                    <p>单位地址：</p>
                    <p>
                        {details.province}
                        {details.city}
                        {details.area}
                        {details.village}
                        {details.street}
                        {details.address}
                    </p>
                </div>
            </div>
            <Form>
                <Form.Item label="时间">
                    <Input type="datetime-local" value={checkTime} onChange={(val) => setCheckTime(val)} />
                </Form.Item>
                <Form.Item label="检查类型">
                    <div className="Add_types">
                        {options.map((e) => (
                            <p
                                onClick={() => {
                                    setTypeIndex((prevArr) => {
                                        if (prevArr.includes(e.id)) {
                                            return prevArr.filter((currentId) => currentId !== e.id)
                                        } else {
                                            return [...prevArr, e.id]
                                        }
                                    })
                                }}
                                key={e.id}
                                className={typeIndex.includes(e.id) ? 'active' : ''}
                            >
                                {e.name}
                            </p>
                        ))}
                    </div>
                </Form.Item>
                <Form.Item label="检查状态">
                    <div className="Add_types">
                        {TAB.map((item) => (
                            <p onClick={() => setStatus(item.val)} key={item.val} className={status === item.val ? 'active' : ''}>
                                {item.title}
                            </p>
                        ))}
                    </div>
                </Form.Item>
            </Form>
            <div className="Add_box">
                <div className="Add_title">
                    <p>检查人员（签名）：</p>
                    <Button color="primary" size="mini" onClick={() => setVisible1(true)}>
                        签名
                    </Button>
                    <Button color="primary" size="mini" onClick={handleButtonClick}>
                        手动上传
                    </Button>
                </div>
                {sign1 ? <Image className="sign_img" height={100} src={sign1} /> : null}
            </div>
            <div className="Add_box">
                <div className="Add_title">
                    <p>被检查单位负责人（签名）：</p>
                    <Button color="primary" size="mini" onClick={() => setVisible2(true)}>
                        签名
                    </Button>
                    <Button color="primary" size="mini" onClick={handleButtonClick2}>
                        手动上传
                    </Button>
                </div>
                {sign2 ? <Image className="sign_img" height={100} src={sign2} /> : null}
            </div>
            <div className="Add_list">
                {record.map((item, index) => (
                    <div className="Add_item" key={index}>
                        <div>
                            <div className="Add_item_text_box">
                                <p>
                                    {index + 1}.{item.title}
                                    <Tag color='#ffc107' style={{ marginLeft: '5px' }}>整改前</Tag>
                                </p>
                                <Button color="danger" size="mini" onClick={() => del(index)}>
                                    删除
                                </Button>
                                {
                                    !rectifyRecord.find(e => e.verifyRecordId === item.id) && item.id ? <Button style={{ marginLeft: '5px' }} color="warning" size="mini" onClick={() => {
                                        reset()
                                        setVisible(true)
                                        setVerifyRecordId(item.id)
                                    }}>
                                        整改
                                    </Button> : null
                                }

                            </div>
                            <Space wrap>
                                {item.imageList.map((e, i) => (
                                    <Image width={110} fit="cover" src={e} key={i} />
                                ))}
                            </Space>
                        </div>
                        {
                            rectifyRecord.find(e => e.verifyRecordId === item.id) ? <div>
                                <div className="Add_item_text_box">
                                    <p>{rectifyRecord.find(e => e.verifyRecordId === item.id).title}<Tag color='green' style={{ marginLeft: '5px' }}>整改后</Tag>
                                    </p>
                                    <Button color="danger" size="mini" onClick={() => del2(rectifyRecord.find(e => e.verifyRecordId === item.id).verifyRecordId)}>
                                        删除
                                    </Button>
                                </div>
                                <Space wrap>
                                    {rectifyRecord.find(e => e.verifyRecordId === item.id).imageList.map((e, i) => (
                                        <Image width={110} fit="cover" src={e} key={i} />
                                    ))}
                                </Space>
                            </div> : null
                        }

                    </div>
                ))}
            </div>

            <div className="Add_btn">
                <Button color="primary" onClick={submit}>
                    保存
                </Button>
                {status === "IN_RECTIFY" ? <Button
                    color="warning"
                    onClick={() => {
                        reset()
                        setVisible(true)
                    }}
                >
                    添加图文描述
                </Button> : null}
            </div>
            {/* 上传 */}
            <input type="file" style={{ display: 'none' }} ref={fileInputRef} onChange={handleFileChange} />
            <input type="file" style={{ display: 'none' }} ref={fileInputRef2} onChange={handleFileChange2} />
            {/* 签名 */}
            <Popup visible={visible1} onMaskClick={reset2} onClose={reset2} bodyStyle={{ height: '35vh' }}>
                <div className="sign_box">
                    <SignatureCanvas penColor="black" canvasProps={{ className: 'sigCanvas' }} ref={sigCanvas} />
                    <div className="sign_btns">
                        <Button color="primary" onClick={() => save(1)}>
                            保存
                        </Button>
                        <Button color="primary" onClick={() => clear(1)}>
                            重新签名
                        </Button>
                    </div>
                </div>
            </Popup>
            <Popup visible={visible2} onMaskClick={reset2} onClose={reset2} bodyStyle={{ height: '35vh' }}>
                <div className="sign_box">
                    <SignatureCanvas penColor="black" canvasProps={{ className: 'sigCanvas' }} ref={sigCanvas2} />
                    <div className="sign_btns">
                        <Button color="primary" onClick={() => save(2)}>
                            保存
                        </Button>
                        <Button color="primary" onClick={() => clear(2)}>
                            重新签名
                        </Button>
                    </div>
                </div>
            </Popup>
            {/* 添加违规记录 */}
            <Popup visible={visible} onMaskClick={reset} onClose={reset} bodyStyle={{ height: '70vh' }}>
                <div className="Add_upload_images">
                    <p>问题描述：</p>
                    <input value={desc} onChange={(e) => setDesc(e.target.value)} className="desc_inp" type="text" placeholder="请输入问题描述" />
                    <p>是否加水印：</p>
                    <Switch value={showWatermark} onChange={setShowWatermark} />
                    {showWatermark ? (
                        <>
                            <p>水印文案：</p>
                            <input value={watermark} onChange={(e) => setWatermark(e.target.value)} className="desc_inp" type="text" placeholder="请输入" />
                        </>
                    ) : null}
                    <p>问题图片：</p>
                    <ImageUploader
                        style={{ '--cell-size': '110px' }}
                        value={fileList}
                        multiple
                        upload={upload}
                        maxCount={maxCount}
                        showUpload={fileList.length < maxCount}
                        onChange={setFileList}
                        onCountExceed={(exceed) => {
                            Toast.show(`最多选择 ${maxCount} 张图片，你多选了 ${exceed} 张`)
                        }}
                    />
                    <Button color="primary" onClick={add}>
                        保存
                    </Button>
                </div>
            </Popup>
        </div>
    )
}

export default SignaturePad
